import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * @author 35326
 * 2021/3/23 20:33
 * 0<=mark<=position<=limit<=capacity
 */
public class TestBuffer {
	public static void main(String[] args) {

	}

	@Test
	public void test1(){
		String string = "abcde";
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		System.out.println("------allocate()-------");
		System.out.println(byteBuffer.position());
		System.out.println(byteBuffer.limit());
		System.out.println(byteBuffer.capacity());

		byteBuffer.put(string.getBytes());
		System.out.println("------put()-------");
		System.out.println(byteBuffer.position());
		System.out.println(byteBuffer.limit());
		System.out.println(byteBuffer.capacity());

		byteBuffer.flip();
		System.out.println("------flip-------");
		System.out.println(byteBuffer.position());//0
		System.out.println(byteBuffer.limit());//5
		System.out.println(byteBuffer.capacity());//1024

		byte[] bytes = new byte[byteBuffer.limit()];
		byteBuffer.get(bytes);
		System.out.println(bytes.toString());
		System.out.println("------get()-------");
		System.out.println(byteBuffer.position());//5
		System.out.println(byteBuffer.limit());//5
		System.out.println(byteBuffer.capacity());//1024

		byteBuffer.rewind();
		//可重复读
		System.out.println("------rewind()-------");
		System.out.println(byteBuffer.position());//0
		System.out.println(byteBuffer.limit());//5
		System.out.println(byteBuffer.capacity());//1024

		//清空缓冲区 但是缓冲区中的数据还在 只是这些数据处于被遗忘状态
		//自己写的知道里面有五个数据
		byteBuffer.clear();
		System.out.println("------clear()-------");
		System.out.println(byteBuffer.position());//0
		System.out.println(byteBuffer.limit());//1024
		System.out.println(byteBuffer.capacity());//1024
	}

	@Test
	public void test2(){
	    //mark:标记：用来记录当前position的位置。可以通过reset()
		//回到mark的位置。
		ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
		byteBuffer.put("abcd".getBytes());
		byteBuffer.flip();
		byte[] bytes = new byte[byteBuffer.limit()];
		byteBuffer.get(bytes,0,2);
		System.out.println(new String(bytes));

		byteBuffer.mark();
		byteBuffer.reset();

		//判断缓冲区中是否还有数据
		if(byteBuffer.hasRemaining()){
			//看看还有几个数据
			System.out.println(byteBuffer.remaining());
		}
	}

	@Test
	/**
	 * 非直接缓冲区：通过alloact()方法分配缓冲区，将缓冲区建立在JVM的内存中
	 * 直接缓冲区：通过allocateDirect()方法分配缓冲区，将缓冲区建立在物理内存中。可能提高效率。
	 */
	public void test3(){
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
		System.out.println(byteBuffer.isDirect());
	}
}
